package day3.HomeWork;

/**
 * ClassName：Test3
 *
 * @Author：小鱼
 * @Create：2025-08-20 19:05
 */
public class Test3 {
    //3.编写代码，实现创建T1、T2、T3三个线程，保证T2在T1执行完后执行，T3在T2执行完后执行。
    //建立锁对象
    static Object mutex = new Object();
    //标记
    static int flag = 1;
    public static void main(String[] args) {
        Thread T1 = new Thread(){
            @Override
            public void run(){
                synchronized (mutex){
                    while (flag!=1){
                        try {
                            mutex.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    for (int i = 1; i < 3; i++) {
                        System.out.println("T1执行了"+i);
                    }
                    flag=2;
                    mutex.notifyAll();
                }
            }
        };
        Thread T2 = new Thread(){
            @Override
            public void run(){
                synchronized (mutex){
                    while (flag!=2){
                        try {
                            mutex.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    for (int i = 3; i < 5; i++) {
                        System.out.println("T2执行了"+i);
                    }
                    flag=3;
                    mutex.notifyAll();
                }
            }
        };
        Thread T3 = new Thread(){
            @Override
            public void run(){
                synchronized (mutex){
                    while (flag!=3){
                        try {
                            mutex.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    for (int i = 5; i < 7; i++) {
                        System.out.println("T3执行了"+i);
                    }
                    flag=1;
                    mutex.notifyAll();
                }
            }
        };
        T1.start();
        T2.start();
        T3.start();
    }
}
